<?php

namespace app\api\controller;

use think\Db;
use think\Hook;
use think\Controller;

class BaseController extends Controller
{
    public function _initialize()
    {
        // // //test
        // $user_info = Db::name('user')->find('5bc57d5b2b913b33190304ce');
        // session('user_info', $user_info);

        if (!request()->isPost()) {
            exit(json_encode(['code' => 1, 'message' => '只允许post请求']));
        }
        $url = input('post.url', '');
        if (!$url) {
            exit(json_encode(['code' => 2, 'message' => '缺少参数：url']));
        }
        $sign = input('post.sign', '');
        if (!$sign) {
            exit(json_encode(['code' => 3, 'message' => '缺少参数：sign']));
        }
        $new_sign = getSign(input('post.'));
        if ($new_sign != $sign) {
            exit(json_encode(['code' => 4, 'message' => '签名错误', 'new_sign' => $new_sign, 'sign' => $sign]));
        }
        if ('weixin/login' != $url) {
            $token = input('post.token', '');
            if (!$token) {
                exit(json_encode(['code' => 5, 'message' => '缺少参数：token']));
            }
            // 缓存
            $user_info = cache('api_user_info_'.$token);
            if (!$user_info) {
                $user_info = Db::name('user')->find($token);
                cache('api_user_info_'.$token, $user_info, 3600);
            }
            if (!$user_info) {
                exit(json_encode(['code' => 6, 'message' => 'token错误']));
            }
            session('user_info', $user_info);
        }
    }
}
